Page({
  data: {
    activeTab: 'single',
    tempFilePath: '',
    result: null,
    loading: false
  },

  switchTab: function(e) {
    this.setData({activeTab: e.currentTarget.dataset.tab});
  },

  chooseImage: function() {
    wx.chooseImage({
      count: 1,
      success: res => {
        this.setData({
          tempFilePath: res.tempFilePaths[0],
          result: null
        });
      }
    });
  },

  uploadImage: function() {
    if (!this.data.tempFilePath) {
        wx.showToast({title: '请先选择图片', icon: 'none'});
        return;
    }

    wx.showLoading({title: '识别中...'});
    wx.uploadFile({
        url: ' https://d6b4-2408-8214-591d-c3d0-e011-4bc6-8965-5fa1.ngrok-free.app/upload', // 确保替换为实际地址
        filePath: this.data.tempFilePath,
        name: 'file',
        success: res => {
            wx.hideLoading();
            try {
                // 检查响应是否为JSON
                if (typeof res.data === 'string' && res.data.startsWith('{')) {
                    const result = JSON.parse(res.data);
                    if (result.success) {
                        this.setData({ result: result.data });
                    } else {
                        wx.showToast({title: result.message || '识别失败', icon: 'none'});
                    }
                } else {
                    throw new Error('无效的响应格式');
                }
            } catch (e) {
                console.error('解析错误:', e);
                wx.showToast({title: '解析结果失败', icon: 'none'});
            }
        },
        fail: err => {
            wx.hideLoading();
            console.error('上传失败:', err);
            wx.showToast({title: `上传失败: ${err.errMsg}`, icon: 'none'});
        }
    });
},

  navigateToCamera: function() {
    wx.navigateTo({url: '/pages/camera/camera'});
  }
});